// 引入express服务器
const express = require('express');
const pool = require('../pool');
// 创建路由器对象
const order = express.Router();

// -------------------1.新增订单------------------------
order.post("/add", (req, res, next) => {
    var obj = req.body;
    // console.log(obj);
       let sql = "INSERT INTO lpk_order (user_id,goods_id,count,addrs_id,status,order_time,pay_time,deliver_time,received_time) VALUES (?,?,?,?,?,?,?,?,?)";
             pool.query(sql, [obj.user_id,obj.goods_id,obj.count,obj.addrs_id,obj.status,obj.order_time,obj.pay_time,obj.deliver_time,obj.received_time], (err, result) => {
          if (err) {
              next(err);
              return;
            }
          res.send({
            code: 200,
            msg:'添加成功'
          })
      })
  })

// -------------------2.订单修改---------------------
order.post("/update",(req,res,next)=>{
    var obj = req.body;
    let sql = "UPDATE lpk_order SET user_id=?,goods_id=?,count=?,addrs_id=?,status=? WHERE oid=?";
    pool.query(sql, [obj.user_id,obj.goods_id,obj.count,obj.addrs_id,obj.status,obj.oid], (err, result) => {
      if (err) {
        next(err);
        return;
      }
      res.send({
        code: 200,
        msg:'更新成功'
      })
    })
  })

  // -------------------3.删除订单---------------------
order.delete("/delete",(req,res,next)=>{
    var obj = req.query;
    let sql = "DELETE FROM lpk_order WHERE oid=?";
    pool.query(sql, [obj.oid], (err, result) => {
      if (err) {
        next(err);
        return;
      }
      res.send({
        code: 200,
        msg:'删除成功'
      })
    })
  })
  
  // ---------------4.查询订单信息------------------
order.post("/details", (req, res, next) => {
  let obj = req.body;
  console.log(obj);
  let sql = 'SELECT * FROM lpk_order WHERE oid=?';
  pool.query(sql, [obj.gid], (err, result) => {
    if (err) {
      next(err);
      return;
    }
    if (result.length == 0) {
      res.send({
        code: 201,
        msg: '查询失败',
      });
    } else {
      res.send({
        code: 200,
        msg: '查询成功',
        data: result,
      });
    }
  })
})
  // ---------------5.查询相关用户的所有订单信息------------------
order.post("/", (req, res, next) => {
  let obj = req.body;
  console.log(obj);
  // let sql = 'SELECT * FROM lpk_order WHERE user_id=?';
  let sql = 'SELECT lpk_order.*,lpk_goods.* FROM (lpk_order INNER JOIN lpk_user ON lpk_order.user_id=lpk_user.lid) INNER JOIN lpk_goods ON lpk_order.goods_id=lpk_goods.gid WHERE lid=?';
  pool.query(sql,[obj.user_id], (err, result) => {
    if (err) {
      next(err);
      return;
    }
    if (result.length == 0) {
      res.send({
        code: 201,
        msg: '查询失败',
      });
    } else {
      res.send({
        code: 200,
        msg: '查询成功',
        data: result,
      });
    }
  })
})
  // 导出路由器对象
  module.exports = order;